#include <iostream>
#include <mutex>
#include "Thread.hpp"
#include<string>
#include<vector>


using namespace Thread_Module;
// int g_tickets = 10000; // 共享资源，没有保护的

// void route(int &tickets)
// {
//     while (true)
//     {
//         if(tickets>0)
//         {
//             usleep(1000);
//             printf("get tickets: %d\n", tickets);
//             tickets--;
//         }
//         else
//         {
//             break;
//         }
//     }
// }

// const int num = 4;
// int main()
// {
//     // std::cout << "main： &tickets: " << &g_tickets << std::endl;

//     std::vector<Thread<int>> threads;
//     // 1. 创建一批线程
//     for (int i = 0; i < num; i++)
//     {
//         std::string name = "thread-" + std::to_string(i + 1);
//         threads.emplace_back(route, g_tickets, name);
//     }

//     // 2. 启动 一批线程
//     for (auto &thread : threads)
//     {
//         thread.Start();
//     }

//     // 3. 等待一批线程
//     for (auto &thread : threads)
//     {
//         thread.Join();
//         std::cout << "wait thread done, thread is: " << thread.threadname() << std::endl;
//     }

//     return 0;
// }


class ThreadData
{
public:
    
    ThreadData(int &tickets,const std::string &name,pthread_mutex_t &mutex)
    :_tickets(tickets)
    ,_name(name)
    ,_total(0)
    ,_mutex(mutex)
    {}
    ~ThreadData()
    {}
public:
    int &_tickets;//总票数的引用
    std::string _name;
    int _total;//线程单独抢的票数
    //std::mutex &_mutex;
    pthread_mutex_t &_mutex;
};
int g_tickets = 10000;//总票数
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;

void scramble(ThreadData *td)//抢票
{
    while(true)
    {
        //pthread_mutex_lock(&gmutex);
        pthread_mutex_lock(&td->_mutex);
        if(td->_tickets > 0)
        {
            usleep(1000);
            std::cout<<"线程："<<td->_name.c_str()<<"正在抢票中..."<<" 抢到的票数是："<<td->_total<<std::endl;
            td->_tickets--;
            // pthread_mutex_unlock(&gmutex);
            pthread_mutex_unlock(&(td->_mutex));

            td->_total++;
        }
        else
        {
            pthread_mutex_unlock(&(td->_mutex));
            //pthread_mutex_unlock(&gmutex);
            break;
        }
    }
}
const int num = 3; 

int main()
{
    
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    std::vector<Thread<ThreadData*>> threads;
    std::vector<ThreadData *> datas;

    //创建一些线程
    for(int i=0;i<num;i++)
    {
        std::string name = "thread - "+std::to_string(i+1);
        ThreadData *td = new ThreadData(g_tickets,name,mutex);
        threads.emplace_back(scramble,td,name);
        datas.emplace_back(td);
    }
    //启动全部线程
    for(auto &thread:threads)
    {
        thread.Start();
    }

    //等待线程
    for(auto &thread:threads)
    {
        thread.Join();
    }

    for(auto data:datas)
    {
        std::cout<<"线程名字:"<<data->_name<<"以及此线程总共抢的票数:"<<data->_total<<std::endl;
        delete data;    
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}